﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using SuperScrollView;
using UnityEngine;
using UnityEngine.UI;

public class BallShaHao : ShaHaoSeter
{
    private Coroutine co;
    protected override void Start()
    {
        uiCompos = GetComponent<UICompos>();


        var shaSingle = uiCompos["shaSingle"].GetComps<Button>();
        var shaZuHe = uiCompos["shaZuHe"].GetComps<Button>();
//        shaMutify
        var shaMutify = uiCompos["shaMutify"].GetComps<Button>();
        var searchMutify = uiCompos["searchMutify"].GetComps<Button>();

        var searchSingle = uiCompos["searchMutify"].GetComps<Button>();
        uiCompos["jiazailishi"].GetComps<Button>().onClick.AddListener(() =>
        {
            SetCurData(GetHistory());
            Deleted();
        });
        uiCompos["saveBtn"].GetComps<Button>().onClick.AddListener(() =>
        {
            List<string> allLines = new List<string>();
            for (int i = 0; i < envCurData.Count; i++)
            {
                var firstData = envCurData[i];
                allLines.Add(
                    $"{firstData[0]} {firstData[1]} {firstData[2]} {firstData[3]} {firstData[4]}");
            }

            File.WriteAllLines(shafileName, allLines);
        });
        shaMutify.onClick.AddListener(() =>
        {
            var shaFile = loadHistoryData(file_dafushi);
            Debug.Log(shaFile);
            List<List<int>> input_nums_array = new List<List<int>>();
            for (int i = 0; i < shaFile.Length; i++)
            {
                var ctx = shaFile[i];
                ctx = ctx.Split('+')[0];
//                ctx = ctx.Replace(" ", "");
                ctx = ctx.Replace('，', ',');
                ctx = ctx.Replace('.', ',');
                ctx = ctx.Replace("、", ",");
//                _queue.Enqueue(ctx);

                List<int> input_nums = GetNums(ctx);
                input_nums_array.Add(input_nums);
            }

            if (co != null)
            {
                StopCoroutine(co);
            }
            co = StartCoroutine(StartShaDaFuShi(input_nums_array));
        });

        shaSingle.onClick.AddListener(() =>
        {
//            StartCoroutine(StartShaDaFuShi());
        });

        shaZuHe.onClick.AddListener(() => { });

        searchMutify.onClick.AddListener(() =>
        {
            Debug.Log("开始搜索");
            var inputs = uiCompos["InputField"].GetComponent<InputField>();
            var inputsTxt = inputs.text;
            inputsTxt = inputsTxt.Split('+')[0];
            inputsTxt = inputsTxt.Replace('，', ',');
            inputsTxt = inputsTxt.Replace('.', ',');
            inputsTxt = inputsTxt.Replace("、", ",");

            string[] strs = inputsTxt.Split(',');
            List<int> list = new List<int>();
            for (int i = 0; i < strs.Length; i++)
            {
                list.Add(int.Parse(strs[i]));
            }

            envCurData = SearchMembers.filterSystem(list, historyData);
            Deleted();
        });

        searchSingle.onClick.AddListener(() => { });
        SetCurData(GetHistory());
        mLoopListView = uiCompos["ShuangseQiu"].GetComps<LoopListView2>();
        mLoopListView.InitListView(envCurData.Count, OnGetItemByIndex);
        uiCompos["delBtn"].GetComponent<Button>().onClick.AddListener(() => { Delected_Select(); });
        uiCompos["random"].GetComponent<Button>().onClick.AddListener(() =>
        {
            var mil = new DateTime(2020, 6, 13, 8, 30, 0).Millisecond;
            System.Random random = new System.Random(mil);

            int len = 10;
            List<List<int>> news_list = new List<List<int>>();
            int start_count = Mathf.CeilToInt(envCurData.Count / (float) len);
            for (int i = 0; i < len; i++)
            {
                var start = start_count * i;
                var end_e = start_count * (i + 1);
                if (end_e > envCurData.Count)
                {
                    end_e = envCurData.Count;
                }

                news_list.Add(envCurData[random.Next(start, end_e)]);
            }

            envCurData = news_list;
            Deleted();
        });
        Deleted();
        
    }


    protected override void Update()
    {
        base.Update();
        uiCompos["Count_Label"].GetComps<Text>().text = envCurData.Count.ToString();

        if (status)
        {
                    ShowProgress("杀号完成");
                    Deleted();
                    status = false;
        }
    }


//    override star
//    fushi_data
    public const string file_dafushi = "shuangseqiu_dafushi.txt";

    public override List<List<int>> GetHistory()
    {
        var shaFile = loadHistoryData(shafileName);
        List<List<int>> input_nums_array = new List<List<int>>();
        for (int i = 0; i < shaFile.Length; i++)
        {
            var ctx = shaFile[i];
            ctx = ctx.Replace(" ", ",");
            ctx = ctx.Replace('，', ',');
            ctx = ctx.Replace('.', ',');
            ctx = ctx.Replace("、", ",");
//                _queue.Enqueue(ctx);

            List<int> input_nums = GetNums(ctx);
            input_nums_array.Add(input_nums);
        }

        return input_nums_array;
    }

    private bool status = false;
    protected new string shafileName = "./shuangseqiu_history.txt";

    public override IEnumerator StartShaDaFuShi(List<List<int>> dafushi_data)
    {
        status = false;
        Task task = Task.Run(async () =>
        {
            await StartTask(dafushi_data);
        });
        yield return task; 
        yield return null;

        selectDic.Clear();
        status = true;
    }
    
    public async Task StartTask(List<List<int>> dafushi_data)
    {
        await Task.Yield();
        List<List<int>> export2Data = Duplex2SingeNote(dafushi_data);
        ShowProgress($"开始杀号 输入了：{dafushi_data.Count} 个数据");
//        ShowProgress($"开始杀号 输入了：{dafushi_data.Count} 个数据");
        var len = Mathf.CeilToInt((float) (export2Data.Count) / const_length);

        for (int sleep_index = 0; sleep_index < len; sleep_index++)
        {
            var cur_max = (sleep_index + 1) * const_length > export2Data.Count
                ? export2Data.Count
                : (sleep_index + 1) * const_length;
            for (int i = sleep_index * const_length; i < cur_max; i++)
            {
                var data = export2Data[i];
                var startIndex = envCurData.FindIndex((elel) =>
                {
                    for (int j = 0; j < data.Count; j++)
                    {
                        if (elel[j] != data[j])
                        {
                            return false;
                        }
                    }

                    return true;
                });
//                Debug.Log($"删除一下 {data[0]} {data[1]}  {data[2]}  {data[3]} {data[4]} {data[5]}");
                if (startIndex != -1)
                {
//                    Debug.Log(
//                        $"删除一下 {envCurData[startIndex][0]} {envCurData[startIndex][1]}  {envCurData[startIndex][2]}  {envCurData[startIndex][3]} {envCurData[startIndex][4]} {envCurData[startIndex][5]}");
                    envCurData.RemoveAt(startIndex);
                }

//                yield return null;
            }

            ShowProgress($"杀号进度 {sleep_index * const_length}");
            
        }
        

    }


    #region 拆数据

    public override List<List<int>> Duplex2SingeNote(List<List<int>> input_nums_array)
    {
        var datas = new List<List<int>>();

        #region 大复式组合成单注

        for (int j = 0; j < input_nums_array.Count; j++)
        {
            List<int> input_nums = input_nums_array[j];
            var max = input_nums.Count;
            for (int i = 1; i <= max - 5; i++)
            {
                for (int i2 = i + 1; i2 <= max - 4; i2++)
                {
                    for (int i3 = i2 + 1; i3 <= max - 3; i3++)
                    {
                        for (int i4 = i3 + 1; i4 <= max - 2; i4++)
                        {
                            for (int i5 = i4 + 1; i5 <= max - 1; i5++)
                            {
                                for (int i6 = i5 + 1; i6 <= max; i6++)
                                {
                                    datas.Add(new List<int>()
                                    {
                                        input_nums[i - 1], input_nums[i2 - 1], input_nums[i3 - 1],
                                        input_nums[i4 - 1],
                                        input_nums[i5 - 1],
                                        input_nums[i6 - 1]
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }

        #endregion

        return datas;
    }

    #endregion
}